import { Config } from "../Config";
import { events } from "../Enums";
import LockScreenUI from "../LockScreenUI";
import { eventMgr } from "./EventMgr";
export interface SendData {
    event: string,
    [t: string]: any
}
export class WSClient {
    private socket: WebSocket;
    private url: string;
    /**心跳时间 */
    private reconnecttime: number = 3000;
    private reconnectNum: number = 10;
    private awaitReconnectNum: number = 0;
    private reconnectTimer: ReturnType<typeof setTimeout>;
    private heartbeatTimeout: ReturnType<typeof setTimeout>;

    // private heartbeatTimeoutSet: boolean;
    public isConnected: boolean;
    constructor(url: string) {
        this.url = url;
        this.reconnectTimer = null;
        console.log(url, "创建长连接")
        this.connect();
    }
    private sendHeartbeat() {
        if (this.socket.readyState !== WebSocket.OPEN) {
            // this.startReconnect();
            return;
        }
        // 发送心跳消息
        this.send({ event: 'ping' });
    }
    private startReconnect() {
        this.stopHeartbeat();
        if (this.awaitReconnectNum >= this.reconnectNum) {
            return;
        }
        // 设置心跳超时定时器
        this.reconnectTimer = setTimeout(() => {
            // 处理心跳超时的情况，比如重新建立连接
            this.awaitReconnectNum++;
            console.log('心跳超时', '正在尝试重新连接...');
            this.stopHeartbeat();
            if (this.socket.readyState !== WebSocket.OPEN) {
                Config.loadstr.show('网络波动，正在重新连接！');
                this.connect();
                return;
            }
        }, this.reconnecttime);
        // 设置超时时间为10秒

    }
    private startHeartbeat(): void {
        this.awaitReconnectNum = 0;
        this.sendHeartbeat();
    }
    // 停止心跳机制
    private stopHeartbeat(): void {
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = null;
        clearTimeout(this.heartbeatTimeout);
        this.heartbeatTimeout = null;
    }

    public async connect(): Promise<void> {
        return new Promise(res => {
            if (this.reconnectTimer) {
                console.log("已经在重连中")
                return; // 已经在重连中
            }
            Config.loadstr.show('正在连接...');
            this.socket = null;
            this.socket = new WebSocket(this.url + "?token=" + Config.TOKEN); // 创建新的 WebSocket 实例
            // 重新绑定事件监听器
            this.socket.onopen = (event: Event) => {
                console.log('WebSocket 已连接', event, this.socket.readyState == WebSocket.OPEN);
                if (this.socket.readyState == WebSocket.OPEN) {
                    this.isConnected = true;
                    // this.send({ action: "onLogin", token: Config.TOKEN, loginKey: Config.Clientkey })
                    // let data = {
                    //     token: Config.TOKEN
                    // }
                    // this.send({ event: "onLogin", data })

                    Config.loadstr.hide();
                    // this.startHeartbeat(); // 启动心跳机制
                    res();
                }
            };
            this.socket.onclose = (event) => {
                console.warn(`WebSocket 连接关闭，代码: ${event.code}, 原因: ${event.reason} `);
                if (!this.isConnected) {
                    // this.stopHeartbeat();
                } else {
                    Config.loadstr.show('连接中断，正在重新连接……');
                    this.connect();
                    // this.startReconnect();
                }
            };
            this.socket.onmessage = (event: MessageEvent) => {
                const message = event.data;
                let ret = JSON.parse(message);
                // if (ret.event != 'pong') {
                if (ret.event) {
                    eventMgr.emit("ws" + ret.event, ret.data);
                } else {
                    // 收到服务器的心跳回应，清除超时定时器并设置下一次心跳发送

                    // clearTimeout(this.heartbeatTimeout);
                    // Config.loadstr.hideStr('网络波动，正在重新连接！');
                    // this.heartbeatTimeout = setTimeout(this.sendHeartbeat.bind(this), this.reconnecttime); // 设置心跳间隔为5秒
                }
            }
            this.socket.onerror = (event: Event) => {
                console.error('WebSocket 错误:', event);
                res();
            }
        })
    }

    public send(message: SendData): void {//
        if (this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(message));
        } else {
            console.warn('WebSocket 连接未打开，无法发送消息:', message);
            if (cc.sys.platform == cc.sys.WECHAT_GAME) {
                eventMgr.emit(events.Toast, '网络连接已中断，即将重启小程序！');
                setTimeout(() => {
                    // 重启小程序
                    wx.restartMiniProgram({});
                }, 2);
            }
        }
    }

    public close(): void {
        this.isConnected = false;
        if (this.socket.readyState === WebSocket.OPEN) {
            this.socket.close(1000, "客户端手动关闭");
        }
    }
}
